#include "imageeditor.h"
#include <QMouseEvent>
#include <QDebug>
#include <QFile>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include "rectitem.h"

ImageEditor::ImageEditor(QWidget *parent) :
    QGraphicsView(parent)
{
    m_drawing = false ;
    QGraphicsScene *scene = new QGraphicsScene(this);
    setScene(scene);
    m_background = new QGraphicsPixmapItem();
    scene->addItem(m_background);
}

void ImageEditor::loadPic(const QString &filename)
{
    removeAllItems();
    QFile file(filename);
    if(file.open(QIODevice::ReadOnly)){
        QPixmap pixmap;
        pixmap.loadFromData(file.readAll());
        file.close();
        m_background->setPixmap(pixmap);
        scene()->setSceneRect(0,0,pixmap.width(),pixmap.height());
    }else{
        qDebug()<<"loadPic,open Error";
    }
}

void ImageEditor::mousePressEvent(QMouseEvent *event)
{
    QGraphicsItem *curItem = itemAt(event->pos());

    if(curItem && curItem->type() == QGraphicsPixmapItem::Type && event->button() & Qt::LeftButton){
        qDebug()<<"new QGraphicsRectItem";
        m_curItem = new RectItem(m_background);
        m_startPoint = mapToScene(event->pos());
        m_drawing = true;
    }
    QGraphicsView::mousePressEvent(event);
}

void ImageEditor::mouseMoveEvent(QMouseEvent *event)
{
    QRect backRect = m_background->pixmap().rect();
    backRect.moveTo(mapFromScene(m_background->scenePos()));
    if(backRect.contains(event->pos())){
        if(m_drawing && event->buttons() & Qt::LeftButton){
            QRectF rect(m_startPoint,mapToScene(event->pos()));
            m_curItem->setRect(checkRectF(rect));
        }
    }
    QGraphicsView::mouseMoveEvent(event);
}

void ImageEditor::mouseReleaseEvent(QMouseEvent *event)
{
    if(m_drawing){
        m_drawing = false ;
        QRectF rc = QRectF(m_startPoint, mapToScene(event->pos())).normalized();
        if(rc.width() * rc.height() < 100){
            scene()->removeItem(m_curItem);
        }else{
            drawEllipse(rc);
        }
    }
    QGraphicsView::mouseReleaseEvent(event);
}

void ImageEditor::drawEllipse(QRectF rc)
{
    QPixmap pixmap = m_background->pixmap();
    QPainter painter(&pixmap);
    painter.setPen(QPen(Qt::blue, 5));
    painter.drawEllipse(rc);
    m_background->setPixmap(pixmap);
}

void ImageEditor::removeAllItems()
{
    QList<QGraphicsItem*>itemList = items();
    foreach (QGraphicsItem *item, itemList) {
        if(item->type() == QGraphicsRectItem::Type){
            scene()->removeItem(item);
        }
    }
}

QRectF ImageEditor::checkRectF(QRectF rc)
{
    QPointF p1 = rc.topLeft() ;
    QPointF p2 = rc.bottomRight() ;

    QPointF r1, r2 ;
    r1.setX(qMin(p1.x(), p2.x()));
    r1.setY(qMin(p1.y(), p2.y()));

    r2.setX(qMax(p1.x(), p2.x()));
    r2.setY(qMax(p1.y(), p2.y()));
    return QRectF(r1,r2);
}
